package com.itheima.health.service.impl;

import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*预约设置*/

@Service
@Slf4j
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    //批量添加
    @Transactional
    @Override
    public void addAll(ArrayList<OrderSetting> orderSettings) {
        log.info("[预约设置-批量添加]data:{}",orderSettings);
        //循环操作
        for (OrderSetting orderSetting : orderSettings) {
            //根据日期批量存入数据库
            editNumberByData(orderSetting.getOrderDate(),orderSetting.getNumber());
        }
    }

    //根据日期批量存入数据库
    private void editNumberByData(Date orderDate, int number) {
        log.info("[预约设置-根据日期编辑]date:{},number:{}", orderDate, number);
        //判断是否存在
        long count = orderSettingDao.countByOrderDate(orderDate);
        if (count>0){
            orderSettingDao.updateById(orderDate,number);
        }else {
            //不存在直接存入
            orderSettingDao.insert(new OrderSetting(orderDate,number));
        }
    }

    //根据月份查询对应预约数据
    @Override
    public List<OrderSetting> getOrderSettingByMonth(Integer year, Integer month) {

        //构造日期范围
        String starDate = String.format("%d-%d-1",year,month);

        String endDate = String.format("%d-%d-31",year,month);


        return orderSettingDao.selectByOrderDateRange(starDate,endDate);
    }

    //根据日期编辑
    @Transactional
    @Override
    public void editNumberByDate(Date orderDate, int number) {
        log.info("[预约设置-根据日期编辑]date:{},number:{}", orderDate, number);
        OrderSetting po = orderSettingDao.selectByOrderDate(orderDate);
        if (null != po) {
            // 存在则更新
            orderSettingDao.updateById(orderDate, number);
        } else {
            // 不存在则插入
            orderSettingDao.insert(new OrderSetting(orderDate, number));
        }
    }

}
